package com.lobstar.xrpc.common;

import java.util.concurrent.TimeUnit;

import com.google.common.cache.Cache;
import com.google.common.cache.CacheBuilder;
import com.google.common.cache.RemovalListener;
import com.google.common.cache.RemovalNotification;
import com.lobstar.xrpc.common.po.Task;
import com.lobstar.xrpc.server.threads.ServerWorkThread;
import com.lobstar.xrpc.service.base.ServiceInvoker;

public class ResponseHandler {
	private Integer size = 100;
	private Integer expire = 10;

	private ResponseHandler() {}
	private ResponseHandler(int size,int expire) {
		this.size = size;
		this.expire = expire;
	}

	public static ResponseHandler build() {
		return new ResponseHandler();
	}
	public static ResponseHandler build(int size,int expire) {
		return new ResponseHandler(size,expire);
	}
	private final Cache<String, Task> responsePool = CacheBuilder.newBuilder()
			.initialCapacity(size)
			.expireAfterWrite(expire, TimeUnit.SECONDS).removalListener(new RemovalListener<String, Task>() {
				@Override
				public void onRemoval(RemovalNotification<String, Task> notification) {
					String key = notification.getKey();
					System.out.println(key+" --remove");
				}
			}).build();

	public void cache(String id,Task task) {
		responsePool.put(id, task);
	}

	public Task get(String id) {
		Task task = responsePool.getIfPresent(id);
		if(task == null) {
			throw new RuntimeException("no response id in cache,maybe timeout");
		}
		return task;
	}
}
